<template>
  <el-drawer
    v-model="dialogVisible"
    title="自然语言生成SQL"
    size="80%"
    :close-on-click-modal="false"
    :before-close="handleClose"
    direction="rtl"
  >
    <div class="sql-generator">
      <!-- 左侧数据库结构 -->
      <div class="left-panel">
        <!-- 添加账套选择 -->
        <div class="tenant-section">
          <div class="panel-header">
            <h3>选择数据库</h3>
          </div>
          <el-select
              filterable
            v-model="selectedTenant"
            placeholder="请选择数据库"
            style="width: 100%"
            @change="handleTenantChange"
          >
            <el-option
              v-for="item in tenantList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>

        <div class="panel-header">
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索表"
              clearable
              @clear="searchKeyword = ''"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button :icon="Search" @click="handleSearchClick"></el-button>
              </template>
            </el-input>
          </div>
        </div>

        <div v-if="tables.length > 0" class="table-stats">
          总表数: {{ tables.length }} | 筛选后: {{ filteredTables.length }}
        </div>

        <div class="table-list-container">
          <el-empty v-if="!selectedTenant" description="请先选择账套"></el-empty>
          <el-empty v-else-if="!isLoadingTables && tables.length === 0" description="暂无数据表"></el-empty>
          <el-empty v-else-if="!isLoadingTables && filteredTables.length === 0" description="没有匹配的表"></el-empty>
          <el-skeleton v-else-if="isLoadingTables" :rows="6" animated />
          <div v-else class="table-list">
            <div v-for="table in filteredTables"
              :key="table.name"
              class="table-item"
              :class="{ 'active': selectedTables.includes(table.name) }"
              @click="toggleTableSelection(table)"
            >
              <div class="table-content">
                <div class="table-info">
                  <el-icon><Grid /></el-icon>
                  <span class="table-name">{{ table.name }}</span>
                  <el-tag v-if="table.hasColumns" size="small" type="success">已加载</el-tag>
                </div>
                <div v-if="table.comment" class="table-comment">
                  <el-tooltip :content="table.comment" placement="top" :show-after="500">
                    <span>{{ table.comment }}</span>
                  </el-tooltip>
                </div>
              </div>
              <div class="table-actions">
                <el-tooltip content="查看表字段" placement="top">
                  <el-button
                    type="primary"
                    circle
                    size="small"
                    @click.stop="loadTableColumns(table)"
                  >
                    <el-icon><View /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>

        <!-- 已选择的表 -->
        <div class="selected-tables" v-if="selectedTables.length > 0">
          <div class="panel-header">
            <h3>已选择的表</h3>
            <div class="selected-actions">
              <el-button type="primary" link @click="loadAllSelectedTableColumns" :disabled="!hasUnloadedSelectedTables">
                加载列信息
              </el-button>
              <el-button type="danger" link @click="clearSelectedTables">
                清空
              </el-button>
            </div>
          </div>
          <div class="selected-tags">
            <el-tag
              v-for="tableName in selectedTables"
              :key="tableName"
              closable
              @close="removeSelectedTable(tableName)"
              :type="getTableColumnsLoadedStatus(tableName) ? 'success' : 'info'"
            >
              {{ tableName }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="right-panel">
        <!-- 自然语言输入区 -->
        <div class="input-section">
          <div class="section-header">
            <h3>查询需求描述</h3>
            <div class="header-actions">
              <el-button size="small" type="info" @click="historyDialogVisible = true">
                <el-icon><Timer /></el-icon>
                历史记录
              </el-button>
              <el-tooltip content="例如：查询用户表中最近7天注册的用户信息，包含用户名和注册时间" placement="top">
                <el-icon class="help-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
              <!-- 添加WebSocket连接状态指示器 -->
              <div class="connection-status" :class="{ connected: isConnected }">
                <el-icon class="status-icon"><Connection /></el-icon>
                {{ isConnected ? 'AI 服务已连接' : '正在连接 AI 服务...' }}
              </div>
            </div>
          </div>
          <el-input
            v-model="naturalLanguage"
            type="textarea"
            :rows="4"
            placeholder="请输入您的查询需求描述..."
            :disabled="isGenerating"
          />
          <div class="prompt-tips">
            <p>提示：描述越详细，生成的SQL越准确。您可以：</p>
            <ul>
              <li>指定具体的表名和字段名</li>
              <li>描述查询条件和过滤规则</li>
              <li>说明需要的排序方式</li>
              <li>指定需要的数据限制</li>
            </ul>
            <div v-if="hasUnloadedSelectedTables" class="warning-tip">
              <el-alert
                type="warning"
                :closable="false"
                show-icon
              >
                <template #title>
                  您选择的表中有部分表的列信息尚未加载，请点击"加载列信息"按钮加载所有表的列信息后再生成SQL。
                </template>
              </el-alert>
            </div>
          </div>
          <div class="action-buttons">
            <el-button
              type="primary"
              :loading="isGenerating"
              :disabled="!selectedTables.length || !naturalLanguage || !isConnected || hasUnloadedSelectedTables"
              @click="handleGenerate"
            >
              生成SQL
            </el-button>
          </div>
        </div>

        <!-- 生成过程 -->
        <div v-if="isGenerating || generatingText" class="generating-section">
          <div class="section-header">
            <h3>生成过程</h3>
          </div>
          <div class="generating-content" ref="generatingContent">
            <pre>{{ generatingText }}</pre>
          </div>
        </div>

        <!-- 生成结果 -->
        <div v-if="generatedSQL" class="result-section">
          <div class="section-header">
            <h3>生成的SQL</h3>
            <div class="actions">
              <el-button type="primary" @click="useGeneratedSQL">
                使用此SQL
              </el-button>
              <el-button @click="handleGenerate">
                重新生成
              </el-button>
            </div>
          </div>
          <div class="sql-content">
            <el-input
              type="textarea"
              v-model="generatedSQL"
              :rows="6"
              readonly
            />
          </div>
        </div>
      </div>

      <!-- 表字段对话框 -->
      <el-dialog
        v-model="columnsDialogVisible"
        :title="currentTable ? currentTable.name + ' 的字段结构' : '字段结构'"
        width="60%"
        append-to-body
      >
        <div class="columns-dialog-content">
          <el-table :data="currentColumns" style="width: 100%">
            <el-table-column prop="name" label="字段名" width="180" />
            <el-table-column prop="type" label="类型" width="120" />
            <el-table-column prop="comment" label="注释" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="insertField(scope.row)"
                >
                  插入
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      <!-- 历史记录对话框 -->
      <el-dialog
        v-model="historyDialogVisible"
        title="SQL生成历史记录"
        width="80%"
        append-to-body
      >
        <div class="history-dialog-content">
          <div v-if="historyList.length === 0" class="empty-history">
            <el-empty description="暂无历史记录"></el-empty>
          </div>
          <el-table v-else :data="historyList" style="width: 100%" border>
            <el-table-column label="查询需求" min-width="200">
              <template #default="scope">
                <div class="history-text">{{ scope.row.requirement }}</div>
              </template>
            </el-table-column>
            <el-table-column label="生成的SQL" min-width="300">
              <template #default="scope">
                <div class="history-sql">{{ truncateText(scope.row.sql, 200) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="生成时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.timestamp) }}
              </template>
            </el-table-column>
            <el-table-column label="数据库" width="120">
              <template #default="scope">
                {{ scope.row.database }}
              </template>
            </el-table-column>
            <el-table-column label="涉及的表" width="180">
              <template #default="scope">
                <el-tag 
                  v-for="table in scope.row.tables" 
                  :key="table" 
                  size="small" 
                  class="history-table-tag"
                >
                  {{ table }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <div class="history-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="useHistory(scope.row)"
                  >
                    使用
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteHistory(scope.$index)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="dialog-footer">
            <el-button @click="historyDialogVisible = false">关闭</el-button>
            <el-button type="danger" @click="clearHistory" :disabled="historyList.length === 0">
              清空历史记录
            </el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/utils/request'
import { Grid, Search, QuestionFilled, Connection, View, Timer } from '@element-plus/icons-vue'
import {useListData} from "@/uses/useListData.js";

const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue', 'generated'])

// 状态变量
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 账套相关
const selectedTenant = ref('')
const isLoadingTables = ref(false)  // 添加加载状态

// 其他状态变量
const searchKeyword = ref('')
const tables = ref([])
const selectedTables = ref([])
const naturalLanguage = ref('')
const isGenerating = ref(false)
const generatingText = ref('')
const generatedSQL = ref('')
const columnsDialogVisible = ref(false)
const currentTable = ref(null)
const currentColumns = ref([])
const {listData: tenantList} = useListData('db_list', {})

// WebSocket相关
const isConnected = ref(false)
let ws = null
let reconnectAttempts = 0
const MAX_RECONNECT_ATTEMPTS = 3

// 添加历史记录相关状态
const historyList = ref([])
const MAX_HISTORY = 10
const historyDialogVisible = ref(false)

// 添加 filteredTables 计算属性
const filteredTables = computed(() => {
  console.log('计算 filteredTables:', {
    tables: tables.value?.length || 0,
    keyword: searchKeyword.value
  })

  if (!tables.value || tables.value.length === 0) return []
  if (!searchKeyword.value) return tables.value

  const keyword = searchKeyword.value.toLowerCase().trim()
  if (!keyword) return tables.value

  const filtered = tables.value.filter(table => {
    const nameMatch = table.name.toLowerCase().includes(keyword)
    const commentMatch = table.comment && table.comment.toLowerCase().includes(keyword)
    return nameMatch || commentMatch
  })

  console.log('筛选结果:', filtered.length)
  return filtered
})

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 初始化 WebSocket 连接
const initWebSocket = () => {
  if (ws?.readyState === WebSocket.OPEN) return

  try {
    // 替换为您的WebSocket服务地址
    ws = new WebSocket('wss://adminstore.saas.nbsaas.com/websocket')

    ws.onopen = () => {
      console.log('WebSocket连接已建立')
      isConnected.value = true
      reconnectAttempts = 0
    }

    ws.onclose = () => {
      console.log('WebSocket连接已关闭')
      isConnected.value = false
      if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
        reconnectAttempts++
        setTimeout(initWebSocket, 1000 * reconnectAttempts)
      } else {
        ElMessage.error('AI 服务连接失败，请稍后重试')
      }
    }

    ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      isConnected.value = false
    }

    ws.onmessage = handleMessage
  } catch (error) {
    console.error('创建WebSocket连接错误:', error)
    isConnected.value = false
  }
}

// 处理WebSocket消息
const handleMessage = (event) => {
  try {
    const data = JSON.parse(event.data)

    if (data.type === 'reply') {
      if (data.messageType === 'reasoning') {
        // 更新思考过程
        window.requestAnimationFrame(() => {
          generatingText.value = (generatingText.value || '') + data.content
          if (generatingContent.value) {
            nextTick(() => {
              generatingContent.value.scrollTop = generatingContent.value.scrollHeight
            })
          }
        })
      } else if (data.messageType === 'content') {
        if (data.content) {
          // 更新生成的SQL - 流式处理
          window.requestAnimationFrame(() => {
            generatedSQL.value = (generatedSQL.value || '') + data.content
          })
        } else {
          // 生成完成
          isGenerating.value = false
          if (generatedSQL.value) {
            // 提取SQL语句
            const extractedSQL = extractSQLFromContent(generatedSQL.value)
            generatedSQL.value = extractedSQL
            // 添加到历史记录
            addHistory(naturalLanguage.value, extractedSQL)
          }
        }
      } else if (data.messageType === 'complete') {
        // 生成完成
        isGenerating.value = false
        if (generatedSQL.value) {
          // 提取SQL语句
          const extractedSQL = extractSQLFromContent(generatedSQL.value)
          generatedSQL.value = extractedSQL
          // 添加到历史记录
          addHistory(naturalLanguage.value, extractedSQL)
        }
      }
    }
  } catch (error) {
    console.error('处理WebSocket消息错误:', error)
  }
}

// 从内容中提取SQL语句
const extractSQLFromContent = (content) => {
  // 尝试提取被```或```sql包裹的SQL代码块
  const codeBlockRegex = /```(?:sql)?([\s\S]*?)```/g
  const matches = [...content.matchAll(codeBlockRegex)]

  if (matches.length > 0) {
    // 返回最后一个代码块（通常是最终的SQL）
    return matches[matches.length - 1][1].trim()
  }

  // 如果没有代码块标记，尝试查找常见的SQL关键字开头的语句
  const sqlKeywordsRegex = /(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH|MERGE|TRUNCATE)[\s\S]+?(?:;|$)/gi
  const keywordMatches = [...content.matchAll(sqlKeywordsRegex)]

  if (keywordMatches.length > 0) {
    // 返回最后一个SQL语句（通常是最终的SQL）
    return keywordMatches[keywordMatches.length - 1][0].trim()
  }

  // 如果以上方法都无法提取，返回原始内容
  return content.trim()
}

// 处理账套变更
const handleTenantChange = async () => {
  // 重置相关状态
  tables.value = []
  selectedTables.value = []
  naturalLanguage.value = ''
  generatingText.value = ''
  generatedSQL.value = ''
  // 加载新账套的表
  await loadTables()
}

// 加载数据库表
const loadTables = async () => {
  if (!selectedTenant.value) {
    ElMessage.warning('请先选择账套')
    return
  }

  isLoadingTables.value = true
  searchKeyword.value = '' // 重置搜索关键字

  try {
    const config = {
      headers: {
        tenant: selectedTenant.value
      }
    }
    const param = {
      model: "table_list",
      filters: {
        db: selectedTenant.value
      }
    }
    const res = await http.post("/data/list", param, config)
    if (res.code === 200) {
      tables.value = res.data.map(table => ({
        name: table.tableName || table.name,
        comment: table.tableComment || table.comment,
        hasColumns: false,
        columns: []
      }))
      console.log(`成功加载 ${tables.value.length} 个数据表`)
      ElMessage.success(`成功加载 ${tables.value.length} 个数据表`)
    } else {
      throw new Error(res.msg || '加载数据表失败')
    }
  } catch (error) {
    console.error('加载数据库表失败:', error)
    ElMessage.error(error.message || '加载数据库表失败')
    tables.value = []
  } finally {
    isLoadingTables.value = false
  }
}

// 加载表字段
const loadTableColumns = async (table, showDialog = true) => {
  if (table.hasColumns) {
    if (showDialog) {
      currentTable.value = table
      currentColumns.value = table.columns
      columnsDialogVisible.value = true
    }
    return table.columns
  }

  try {
    const config = {
      headers: {
        tenant: selectedTenant.value
      }
    }
    const param = {
      model: "column_list",
      filters: {
        db: selectedTenant.value,
        table: table.name
      }
    }
    const res = await http.post("/data/list", param, config)
    if (res.code === 200) {
      const columns = res.data.map(col => ({
        name: col.columnName || col.name,
        type: col.dataType || col.type,
        comment: col.columnComment || col.comment,
        isPrimary: col.isPrimary === true,
        isNullable: col.nullable === true
      }))

      // 更新表的字段信息
      const tableIndex = tables.value.findIndex(t => t.name === table.name)
      if (tableIndex !== -1) {
        tables.value[tableIndex].columns = columns
        tables.value[tableIndex].hasColumns = true
      }

      if (showDialog) {
        currentTable.value = table
        currentColumns.value = columns
        columnsDialogVisible.value = true
      }

      return columns
    }
  } catch (error) {
    console.error('加载表字段失败:', error)
    if (showDialog) {
      ElMessage.error('加载表字段失败')
    }
    return []
  }
}

// 切换表选择
const toggleTableSelection = async (table) => {
  const index = selectedTables.value.indexOf(table.name)
  if (index === -1) {
    // 添加到选中列表前，确保列信息已加载
    if (!table.hasColumns) {
      try {
        ElMessage.info(`正在加载表 ${table.name} 的列信息...`)
        await loadTableColumns(table, false)
        ElMessage.success(`表 ${table.name} 的列信息加载完成`)
      } catch (error) {
        ElMessage.error(`加载表 ${table.name} 的列信息失败，请重试`)
        return
      }
    }
    selectedTables.value.push(table.name)
  } else {
    selectedTables.value.splice(index, 1)
  }
}

// 移除选中的表
const removeSelectedTable = (tableName) => {
  const index = selectedTables.value.indexOf(tableName)
  if (index !== -1) {
    selectedTables.value.splice(index, 1)
  }
}

// 清空选中的表
const clearSelectedTables = () => {
  selectedTables.value = []
}

// 插入字段到查询描述
const insertField = (field) => {
  if (!currentTable.value) return

  const fieldText = `${currentTable.value.name}.${field.name}`
  const textarea = document.querySelector('.input-section textarea')
  if (!textarea) return

  const cursorPos = textarea.selectionStart
  const textBefore = naturalLanguage.value.substring(0, cursorPos)
  const textAfter = naturalLanguage.value.substring(cursorPos)

  naturalLanguage.value = `${textBefore}${fieldText}${textAfter}`

  ElMessage.success(`已插入字段 ${fieldText}`)
}

// 确保所有选中表的列信息已加载
const prepareTablesForGeneration = async () => {
  const tablesNeedColumns = selectedTables.value.filter(tableName => {
    const table = tables.value.find(t => t.name === tableName)
    return table && !table.hasColumns
  })

  if (tablesNeedColumns.length > 0) {
    isGenerating.value = true
    generatingText.value = '正在加载表结构信息...\n'

    try {
      for (const tableName of tablesNeedColumns) {
        const table = tables.value.find(t => t.name === tableName)
        if (table) {
          generatingText.value += `加载表 ${tableName} 的结构...\n`
          // 不显示对话框，只加载列信息
          await loadTableColumns(table, false)
          generatingText.value += `表 ${tableName} 结构加载完成\n`
        }
      }

      generatingText.value += '所有表结构加载完成，开始生成SQL...\n'
    } catch (error) {
      console.error('加载表列信息失败:', error)
      ElMessage.error('加载表列信息失败，请重试')
      isGenerating.value = false
      return false
    }
  }

  return true
}

// 生成SQL
const handleGenerate = async () => {
  if (!selectedTenant.value) {
    ElMessage.warning('请先选择账套')
    return
  }

  if (!naturalLanguage.value) {
    ElMessage.warning('请输入查询需求描述')
    return
  }

  if (selectedTables.value.length === 0) {
    ElMessage.warning('请选择至少一个表')
    return
  }

  if (!isConnected.value) {
    ElMessage.warning('AI 服务未连接，请稍后重试')
    return
  }

  // 检查是否所有选中的表都已加载列信息
  const unloadedTables = selectedTables.value.filter(tableName => {
    const table = tables.value.find(t => t.name === tableName)
    return table && !table.hasColumns
  })

  if (unloadedTables.length > 0) {
    ElMessage.warning(`以下表的列信息尚未加载: ${unloadedTables.join(', ')}，请先加载列信息`)
    return
  }

  isGenerating.value = true
  generatingText.value = '正在分析您的需求...\n'
  generatedSQL.value = ''

  try {
    // 准备数据库结构信息
    const dbStructure = {
      tables: tables.value
        .filter(table => selectedTables.value.includes(table.name))
        .map(table => ({
          name: table.name,
          comment: table.comment || '',
          columns: table.columns.map(col => ({
            name: col.name,
            type: col.type,
            comment: col.comment || '',
            isPrimary: col.isPrimary,
            isNullable: col.isNullable
          }))
        }))
    }

    // 使用WebSocket发送请求
    if (ws && ws.readyState === WebSocket.OPEN) {
      const message = {
        type: 'prompt',
        message: `我需要根据以下数据库结构生成SQL查询：\n\n${JSON.stringify(dbStructure, null, 2)}\n\n用户需求：${naturalLanguage.value}\n\n请生成符合需求的SQL查询语句。`,
        stream: true
      }

      ws.send(JSON.stringify(message))
    } else {
      // 如果WebSocket不可用，回退到HTTP请求
      const config = {
        headers: {
          tenant: selectedTenant.value
        }
      }

      const param = {
        model: "generate_sql",
        filters: {
          dbStructure: dbStructure,
          requirement: naturalLanguage.value
        }
      }

      const res = await http.post("/ai/generate", param, config)

      if (res.code === 200) {
        generatedSQL.value = res.data.sql
        generatingText.value = res.data.explanation
        // 添加到历史记录
        addHistory(naturalLanguage.value, res.data.sql)
        ElMessage.success('SQL生成成功')
      } else {
        throw new Error(res.msg || '生成SQL失败')
      }

      isGenerating.value = false
    }
  } catch (error) {
    console.error('生成SQL失败:', error)
    ElMessage.error(error.message || '生成SQL失败')
    isGenerating.value = false
  }
}

// 使用生成的SQL
const useGeneratedSQL = () => {
  emit('generated', generatedSQL.value)
  handleClose()
  ElMessage.success('已应用生成的SQL')
}

// 关闭对话框
const handleClose = () => {
  if (isGenerating.value) {
    ElMessageBox.confirm('正在生成SQL，确定要取消吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      isGenerating.value = false
      dialogVisible.value = false
    }).catch(() => {})
    return
  }
  dialogVisible.value = false
}

// 监听对话框显示状态
watch(() => dialogVisible.value, (newVal) => {
  if (newVal) {
    // 重置状态
    searchKeyword.value = ''
    selectedTables.value = []
    naturalLanguage.value = ''
    generatingText.value = ''
    generatedSQL.value = ''

    // 初始化WebSocket连接
    if (!isConnected.value) {
      initWebSocket()
    }

    // 如果已经选择了账套，加载数据表
    if (selectedTenant.value) {
      loadTables()
    }
  }
})

// 监听搜索关键字变化
const handleSearchChange = debounce(() => {
  console.log('搜索关键字变化(防抖后):', searchKeyword.value)
}, 300)

watch(() => searchKeyword.value, () => {
  console.log('搜索关键字变化(原始):', searchKeyword.value)
  handleSearchChange()
})

// 组件挂载时加载数据
onMounted(() => {
  if (dialogVisible.value) {
    initWebSocket()
    if (selectedTenant.value) {
      loadTables()
    }
  }
  
  // 加载历史记录
  loadHistory()
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (ws) {
    ws.close()
    ws = null
  }
  
  // 保存历史记录
  saveHistory()
})

// 处理搜索按钮点击
const handleSearchClick = () => {
  console.log('搜索按钮点击:', searchKeyword.value)
  // 强制重新计算筛选结果
  const keyword = searchKeyword.value
  searchKeyword.value = ''
  nextTick(() => {
    searchKeyword.value = keyword
  })
}

// 获取表的列信息加载状态
const getTableColumnsLoadedStatus = (tableName) => {
  const table = tables.value.find(t => t.name === tableName)
  return table && table.hasColumns
}

// 计算是否有未加载列信息的选中表
const hasUnloadedSelectedTables = computed(() => {
  return selectedTables.value.some(tableName => {
    const table = tables.value.find(t => t.name === tableName)
    return table && !table.hasColumns
  })
})

// 加载所有选中表的列信息
const loadAllSelectedTableColumns = async () => {
  if (selectedTables.value.length === 0) {
    ElMessage.warning('请先选择表')
    return
  }

  const tablesNeedColumns = selectedTables.value.filter(tableName => {
    const table = tables.value.find(t => t.name === tableName)
    return table && !table.hasColumns
  })

  if (tablesNeedColumns.length === 0) {
    ElMessage.info('所有选中的表已加载列信息')
    return
  }

  try {
    ElMessage.info(`正在加载 ${tablesNeedColumns.length} 个表的列信息...`)

    for (const tableName of tablesNeedColumns) {
      const table = tables.value.find(t => t.name === tableName)
      if (table) {
        await loadTableColumns(table, false)
      }
    }

    ElMessage.success('所有选中表的列信息加载完成')
  } catch (error) {
    console.error('加载表列信息失败:', error)
    ElMessage.error('加载表列信息失败，请重试')
  }
}

// 从localStorage加载历史记录
const loadHistory = () => {
  try {
    const saved = localStorage.getItem('sqlGeneratorHistory')
    if (saved) {
      historyList.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 保存历史记录到localStorage
const saveHistory = () => {
  try {
    localStorage.setItem('sqlGeneratorHistory', JSON.stringify(historyList.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
  }
}

// 添加历史记录
const addHistory = (requirement, sql) => {
  // 检查是否已存在相同的记录
  const isDuplicate = historyList.value.some(item =>
    item.requirement === requirement && item.sql === sql
  )

  // 如果是重复记录，则不保存
  if (isDuplicate) {
    return
  }

  // 添加新记录
  historyList.value.unshift({
    requirement,
    sql,
    timestamp: new Date().toISOString(),
    database: selectedTenant.value,
    tables: selectedTables.value
  })

  // 限制历史记录数量
  if (historyList.value.length > MAX_HISTORY) {
    historyList.value = historyList.value.slice(0, MAX_HISTORY)
  }

  saveHistory()
}

// 删除单条历史记录
const deleteHistory = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除这条历史记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    historyList.value.splice(index, 1)
    saveHistory()
    ElMessage.success('已删除历史记录')
  } catch (error) {
    // 用户取消删除
  }
}

// 清空历史记录
const clearHistory = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有历史记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    historyList.value = []
    saveHistory()
    ElMessage.success('已清空历史记录')
  } catch (error) {
    // 用户取消清空
  }
}

// 使用历史记录
const useHistory = (item) => {
  naturalLanguage.value = item.requirement
  generatedSQL.value = item.sql
  
  // 如果历史记录中的数据库与当前选择的不同，提示用户
  if (item.database && item.database !== selectedTenant.value) {
    ElMessage.warning(`此记录使用的数据库(${item.database})与当前选择的不同，可能需要重新选择相关表`)
  }
  
  // 关闭历史记录对话框
  historyDialogVisible.value = false
}

// 格式化时间
const formatTime = (isoString) => {
  try {
    const date = new Date(isoString)
    return date.toLocaleString()
  } catch (error) {
    return isoString
  }
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}
</script>

<style scoped>
.sql-generator {
  display: flex;
  height: 100%;
  gap: 20px;
  padding: 20px;
}

.left-panel {
  width: 300px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tenant-section {
  margin-bottom: 10px;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.table-list-container {
  flex: 1;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.table-list {
  padding: 10px;
  overflow-y: auto;
  max-height: 100%;
}

.table-item {
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.table-item:hover {
  background-color: #f5f7fa;
}

.table-item.active {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.table-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.table-name {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
}

.table-comment {
  font-size: 12px;
  color: #909399;
  margin-left: 24px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table-actions {
  margin-left: 8px;
  display: flex;
  align-items: center;
}

.selected-tables {
  border-top: 1px solid #dcdfe6;
  padding-top: 20px;
}

.selected-actions {
  display: flex;
  gap: 8px;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tags .el-tag {
  margin-right: 0;
  display: flex;
  align-items: center;
}

.selected-tags .el-tag.el-tag--success {
  background-color: #f0f9eb;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.help-icon {
  color: #909399;
  cursor: pointer;
}

.prompt-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.prompt-tips p {
  margin: 0 0 8px 0;
  font-weight: 500;
}

.prompt-tips ul {
  margin: 0;
  padding-left: 20px;
  margin-bottom: 10px;
}

.prompt-tips li {
  margin-bottom: 4px;
  color: #606266;
}

.input-section {
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.generating-section {
  flex: 1;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 20px;
}

.generating-content {
  padding: 16px;
  height: 200px;
  overflow-y: auto;
  background-color: #f8f9fa;
}

.generating-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
}

.result-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
  background-color: #fff;
}

.sql-content {
  margin-top: 16px;
}

.sql-content :deep(.el-textarea__inner) {
  font-family: monospace;
  font-size: 14px;
  line-height: 1.6;
}

.columns-dialog-content {
  max-height: 500px;
  overflow-y: auto;
}

/* WebSocket连接状态样式 */
.connection-status {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #909399;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.connection-status.connected {
  color: #67c23a;
  background-color: #f0f9eb;
}

.status-icon {
  font-size: 14px;
}

.table-stats {
  margin-bottom: 10px;
  font-size: 12px;
  color: #909399;
}

.search-container {
  width: 100%;
}

.warning-tip {
  margin-top: 10px;
}

.history-dialog-content {
  max-height: 500px;
  overflow-y: auto;
}

.actions {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.history-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-sql {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-table-tag {
  margin-right: 4px;
}

.history-actions {
  display: flex;
  gap: 8px;
}

.dialog-footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
